import React,{useState,useEffect} from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Button, Card, Form, Input, Space, Typography,Divider,Modal,Select,InputNumber,message,Radio,AutoComplete  } from 'antd';
import { useNavigate } from 'react-router-dom';
import Loading from '@/components/Loading/index.tsx';
import EditGoods from '@/components/EditGoods/index.tsx';

import styles from './index.module.scss';
import { req,formaData } from '@/common/methods';

interface TypeProps{
  method:'in' | 'out';
}

let baseData = {};
const  baseDataToOpt = () => {
  const res = [];
  for(let key in baseData){
    res.push({
      value:key,
      label:baseData[key]['name']
    })
  }
  return res;
}
let timerForSearch:number|undefined = undefined;
const StorageAdd: React.FC<TypeProps> = (props:TypeProps) => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const isIn = props && props.method && (props.method === 'in');
  const [vMethod,setVMethod] = useState(isIn?10:20);
  const isSup = () => {
    //console.log('调用了isSup',vMethod);
    return Math.floor(vMethod / 10) == 1
  };
  //console.log(vMethod);
  const [loading,setLoading] = useState(true);
  const [idInp,setIdInp] = useState({});
  const [allDepartForInput,setAllDepartForInput] = useState([]);
  const reqBaseData = () => {
    setLoading(true);
    req('/api/goods/easy_get').then((data:any) => {
      baseData = {...data};
      //setLoading(false);
      return req(`/api/${isSup()?'suppliers':'depart'}/get`);
    }).then((data:any) => {
      //console.log('所有部门',data);
      setAllDepartForInput(data.map((item:any) => ({
        ...item,
        value:item.id,
        label:item.local ? `${item.name}(${item.local})` : item.name,
        includes:item.includes ? ('' + item.includes).split(' ') : []
      })));
    }).catch((err)=>{
      Modal.error({
        title:'初始化错误',
        content:<>无法获取基础数据<br/>{''+err}</>
      });
    }).finally(()=>setLoading(false));
  }
  useEffect(()=>{
    reqBaseData();
  },[vMethod]);
  const onFinish = (values:any) => {
    //console.log('finish',values)
    setSubmitButtonDisabled(true);
    try{
      //console.log(values);
      if(!values || !values.items || !values.items[0]){
        Modal.error({title:'错误',content:<>参数无效</>});
      }
      //将数据处理成对应的格式
      const val = values.items[0];
      const res:any[] = [];
      if(!val.data || (typeof val.data === 'object' &&  Array.isArray(val.data) && val.data.length === 0)){
        Modal.error({
          title:'错误',
          content:<>清单为空，无法添加单据</>,
          onOk(){
            setSubmitButtonDisabled(false);
          },
          onCancel(){
            setSubmitButtonDisabled(false);
          },
        });
      }else{
        val.data.forEach((item:any) => {
          res.push({
            ...item,
            time:formaData(new Date()),
            method:val.method,//isIn?10:20,
            depart:val.depart,
            requ:val.requ,
            empl:val.empl,
            change_count:isIn?item.change_count:(0-item.change_count)
          })
        });
        
        req('/api/storage',{data:JSON.stringify(res)},'post').then((data) => {
          Modal.success({
            title:'提交成功',
            content:<>您的{isIn?'入':'出'}库单已提交</>,
            onOk(){
              navigate(`/management/lib/${isIn?'in':'out'}_storage`)
            }
          })
        }).catch((err) => {
          Modal.error({
            title:'操作失败',
            content:<>{''+err}</>
          })
          setSubmitButtonDisabled(false);
        }).finally(()=>{
          //
        })
        //()=>setSubmitButtonDisabled(false)
      }

      //console.log(res);
    }catch(e){
      Modal.error({title:'系统出现严重错误',content:<>{''+e}</>});
    }
  }
  const onFinishFailed = (errorInfo: any) => {
    Modal.error({
        title:'提交失败',
        content:<>
          <div>信息未能正常提交，请检查！参考：{typeof errorInfo === 'object' ? JSON.stringify(errorInfo || {}) : ''+errorInfo}</div>
        </>,
    })
  };
  const [goodsInputData,setGoodsInputData] = useState([]);
  const [goodsInputValue,setGoodsInputValue] = useState('');

  const handleGoodsChange = (newValue,key) => {
    setGoodsInputValue(''+newValue);
    //console.log(newValue,key);
    //console.log(baseData[newValue]);
    setIdInp({...idInp,[key]:newValue});
  }
  const handleGoodsSearch = (newValue) => {
    //console.log('search',newValue);
    clearTimeout(timerForSearch);
    timerForSearch = setTimeout(()=>{
      req('/api/goods/get_all',{search:newValue.trim()},'get').then((data) => {
        //console.log('获取',data);
        setGoodsInputData(data.map(item => ({
          value:item.id,
          label:item.name// + (newValue ? `(${newValue})` : '')
        })))
      }).catch((error)=>{
        //console.log('未获取',error);
        message.error('未获取数据' + error);
      });
    },500);
  }
  const [vEmpl,setVEmpl] = useState('');
  const [isSubmitButtonDisabled,setSubmitButtonDisabled] = useState(false);
  const [requMembers,setRequMembers] = useState([]);//成员信息
  
  return (
    <>
    {loading ? <>
      <Loading/>
    </>: <Form
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      form={form}
      name="dynamic_form_complex"
      //style={{ maxWidth: 600 }}
      autoComplete="off"
      initialValues={{ items: [{}] }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.List name="items">
        {(fields, { add, remove }) => (
          <div style={{ display: 'flex', rowGap: 16, flexDirection: 'column' }}>
            {fields.map((field) => (
              <Card
                size="large"
                title={`新增${isIn?'入':'出'}库单`}
                key={field.key}
                extra={
                  <CloseOutlined
                    onClick={() => {
                      //remove(field.name);
                      navigate(`/management/lib/${isIn?'in':'out'}_storage`);
                    }}
                  />
                }
              >
                <div className={styles.formt} >
                  <Form.Item label={(isIn?'入':'出') + '库方式'} name={[field.name, 'method']} rules={[{required:true,message:'方式不能为空'}]} initialValue={vMethod}>
                    <Radio.Group onChange={(e)=>{
                      setVMethod(e.target.value);
                    }} value={vMethod}>
                      <Radio value={10}>{isIn?'进货':'退货'}</Radio>
                      <Radio value={20}>{isIn?'收回':'领用'}</Radio>
                    </Radio.Group>
                  </Form.Item>
                  <Form.Item label={isSup()?'供货商':'部门'} name={[field.name, 'depart']} rules={[{required:true,message:'部门名称不能为空'}]}>
                    <Select showSearch
                      placeholder={`选择${isSup()?'供货商':'部门'}`}
                      optionFilterProp="children"
                      //onChange={onChange}
                      //onSearch={onSearch}
                      filterOption={(input: string, option: { label: string; value: string }) =>
                      (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                      options={[...allDepartForInput]}
                      onChange={(value) => {
                        setRequMembers((()=>{
                          const find = allDepartForInput.find(item => item.id === value);
                          if(!find || !find.includes || !Array.isArray(find.includes)){
                            return [];
                          }else{
                            return find.includes.map(item1 => ({value:item1}));
                          }
                        })())
                      }}
                      // defaultActiveFirstOption={false}
                      // suffixIcon={null}
                      // filterOption={false}
                  />
                  </Form.Item>
                  <Form.Item label={isSup()?( (isIn?'进':'退') + '货人'):'申请人'} name={[field.name, 'requ']} rules={isSup()?[]:[{required:true,message:'申请人不能为空'}]} onBlur={(e)=>{
                    //setVEmpl(e.target.value);
                    //console.log('执行了',e.target.value);
                    //这里要实现的功能，当申请人失去焦点，领用人
                    const fieldsValue = {...form.getFieldsValue()};
                    if(fieldsValue.items && fieldsValue.items[0] && !fieldsValue.items[0].empl){
                      fieldsValue.items[0].empl = e.target.value;
                    }
                    form.setFieldsValue({...fieldsValue});
                  }} >
                    <AutoComplete options={requMembers}/>
                    {/* <Input autoComplete='true' /> */}

                  </Form.Item>
                  <Form.Item label={isSup()?'确认人':(isIn?'交回人':'领用人')} name={[field.name, 'empl']} rules={isSup()?[]:[{required:true,message:'领用人不能为空'}]} onChange={e=>{
                    //setVEmpl(e.target.value);
                    //console.log('执行了onchange',e.target.value,vEmpl);
                  }}>
                    <AutoComplete options={requMembers}/>
                    {/* <Input autoComplete='true'  /> */}
                    {/* value={vEmpl} */}
                  </Form.Item>
                </div>
                <Divider orientation="center">清单</Divider>
                {/* Nest Form.List */}
                <div className={styles['nest-form-list']}>
                  <Form.Item label="">
                    <Form.List name={[field.name, 'data']}>
                      {(subFields, subOpt) => (
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          {subFields.map((subField) => (
                            // <Space key={subField.key}>
                            <div className={styles['form-list-pkg']} key={subField.key}>
                              {(isSup()&&isIn) && <>
                                <Button size="small" onClick={((k) => (e) =>{
                                  console.log(k);
                                  const fieldsValue = {...form.getFieldsValue()};
                                  if(!fieldsValue.items){
                                    fieldsValue.items = [];
                                  }
                                  if(!fieldsValue.items[0]){
                                    fieldsValue.items[0] = {};
                                  }
                                  if(!fieldsValue.items[0].data){
                                    fieldsValue.items[0].data = [];
                                  }
                                  if(!fieldsValue.items[0].data[k]){
                                    fieldsValue.items[0].data[k] = {};
                                  }
                                  req('/api/category/get').then(categoryData => {
                                    Modal.info({
                                      title:'新增物品',
                                      content:<>
                                        <EditGoods ty='create' defaultData={{}} doClose={(data)=>{
                                          // console.log(data);
                                          //alert('调用了',data);
                                          if(data[0] && data[0].id){
                                            fieldsValue.items[0].data[k].goods_id = data[0].id;
                                          }
                                          req('/api/goods/easy_get').then(reqbaseData => {
                                            //console.log(data[0]);
                                            baseData = {...reqbaseData};
                                            handleGoodsSearch('' + data[0].name);
                                            handleGoodsChange(data[0].id,k)
                                            form.setFieldsValue({...fieldsValue});
                                            console.log({...fieldsValue});
                                          }).catch((error)=>{
                                              Modal.error({
                                                title:'错误',
                                                content:<>无法检索基本的物品信息，操作失败{''+error}</>
                                              })
                                          })
                                        }} dataCategory={categoryData}/>
                                      </>,
                                      footer:false
                                    })
                                  }).catch((error)=>{
                                    Modal.error({
                                      title:'错误',
                                      content:<>无法获取类别数据，操作失败{''+error}</>
                                    })
                                  })
                                })(subField.key)}>新增物品</Button>
                              </>}
                              <Form.Item label="物品" name={[subField.name, 'goods_id']}  rules={[{required:true,message:'物品不能为空'}]}>
                                <Select
                                  showSearch
                                  placeholder="选择物品"
                                  //optionFilterProp="children"
                                  //onChange={onChange}
                                  //onSearch={onSearch}
                                  filterOption={(input: string, option?: { label: string; value: string }) =>
                                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())}
                                  //options={baseDataToOpt(baseData)}
                                  options={goodsInputData}
                                  onChange={(values) => handleGoodsChange(values,subField.key)}
                                  onSearch={handleGoodsSearch}
                                  defaultActiveFirstOption={false}
                                  suffixIcon={null}
                                  //filterOption={false}
                                />
                              </Form.Item>
                              {/* <Form.Item label="ID" name={[subField.name, 'goods_id']}  rules={[{required:true,message:'惟一标识符不能为空'}]}>
                                <Input placeholder="物品ID" onChange={(e)=>{
                                  //console.log(e.target.value,subField.key)
                                  setIdInp({...idInp,[subField.key]:e.target.value});
                                }} />
                              </Form.Item> */}
                              <div className={styles['form-diy-area']}>
                                <nobr>规格:</nobr>
                                {/* {baseData[idInp[subField.key]] ? baseData[idInp[subField.key]].specs : '(未知)'} */}
                                <Input placeholder="规格" value={baseData[idInp[subField.key]] ? baseData[idInp[subField.key]].specs : '(未知)'} disabled/>
                              </div>
                              <div className={styles['form-diy-area']}>
                                <nobr>单位:</nobr>
                                {/* {baseData[idInp[subField.key]] ? baseData[idInp[subField.key]].unit : '(未知)'} */}
                                <Input placeholder="单位" value={baseData[idInp[subField.key]] ? baseData[idInp[subField.key]].unit : '(未知)'} disabled/>
                              </div>
                              {/* <Form.Item label="物品" name={[subField.name, 'goods_name']}  value={'123'}>
                                <Input placeholder="物品名称" defaultValue="222222" disabled/>
                              </Form.Item>
                              <Form.Item label="单位" name={[subField.name, 'goods_unit']}>
                                <Input placeholder="单位" disabled/>
                              </Form.Item> */}
                              <Form.Item label="数量" name={[subField.name, 'change_count']} rules={[{required:true,message:'数量不能为空'},{type: 'integer', min:1, message: '数量最低为1' },(baseData[idInp[subField.key]] && baseData[idInp[subField.key]].count && !isIn) ?  {type: 'integer', max:baseData[idInp[subField.key]].count, message: '数量不得超出库存' } : {type: 'integer', max:10000, message: '数量不得超出10000'} ]}>
                                <InputNumber addonBefore="" addonAfter={<><span style={{padding:'0 1em'}}>(库存:{baseData[idInp[subField.key]] ? baseData[idInp[subField.key]].count : '(未知)'})</span></>} />
                                {/* <Input placeholder="数量" /> */}
                                
                              </Form.Item>
                              <Form.Item label="备注" name={[subField.name, 'remark']}>
                                <Input placeholder={`备注[${idInp[subField.key] || ''}]`} />
                              </Form.Item>
                              <CloseOutlined
                                onClick={() => {
                                  subOpt.remove(subField.name);
                                }}
                              />
                            </div>
                            // </Space>
                          ))}
                          <Button type="dashed" onClick={() => subOpt.add()} block>
                            + 增加一栏
                          </Button>
                        </div>
                      )}
                    </Form.List>
                  </Form.Item>
                </div>
              </Card>
            ))}

            {/* <Button type="dashed" onClick={() => add()} block>
              + Add Item
            </Button> */}
          </div>
        )}
      </Form.List>
      <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" style={{width:'375px',margin:'auto'}} disabled={isSubmitButtonDisabled}>
              提交{isIn?'入':'出'}库
          </Button>
      </Form.Item>
      <div style={{visibility:'visible'}}>
        <Form.Item noStyle shouldUpdate>
          {() => (
            <Typography>
              <pre>{JSON.stringify(form.getFieldsValue(), null, 2)}</pre>
            </Typography>
          )}
        </Form.Item>

      </div>

    </Form>}
    </>
  );
};

export default StorageAdd;